package com.ah.shanxi_demo.service.impl;

import com.ah.shanxi_demo.common.enums.SXPortEnum;
import com.ah.shanxi_demo.entity.SxRegister;
import com.ah.shanxi_demo.mapper.SxRegisterMapper;
import com.ah.shanxi_demo.mapper.SxSyncMapper;
import com.ah.shanxi_demo.service.IRegisterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author zt 2020/8/10
 */
@Service("registerService")
public class RegisterService implements IRegisterService {
    private static final Logger logger = LoggerFactory.getLogger(RegisterService.class);

    public static final String register_url="/nodes/register";


    @Autowired
    private SxRegisterMapper registerMapper;

    @Autowired
    private SxSyncMapper syncMapper;

    public static void main(String[] args) {

        String url_register="https://192.168.1.12:8081/api/v1/nodes/register";

        String replace = url_register.replace(SXPortEnum.REGISTER.getKey(),"");
        System.out.println(replace);

    }

    @Override
    @Transactional
    public SxRegister insert(SxRegister sxRegister) {
        //部级平台注册成功 返回center_key 节点唯一标识
//        String centerKey = register_client(sxRegister);
        String centerKey="test_key";
        if (null==centerKey){
            return null;
        }

        //部级平台注册成功 插入数据库
        sxRegister.setCenterKey(centerKey);
        sxRegister.setServiceAddress(sxRegister.getServiceAddress().replace(SXPortEnum.REGISTER.getKey(),""));
        registerMapper.insertRegister(sxRegister);

        //新增同步表 与注册表保持一致
        try {
            syncMapper.insertSync(sxRegister.getRegisterId());
        }catch (Throwable e){
            System.out.println(e.getMessage());
        }

        sxRegister.setServiceAddress(sxRegister.getServiceAddress()+SXPortEnum.REGISTER.getKey());
        return sxRegister;
    }

    @Override
    public SxRegister queryRecent() {
        SxRegister sxRegister = registerMapper.selectRecent();
        if (sxRegister==null){
            return new SxRegister();
        }
        sxRegister.setServiceAddress(sxRegister.getServiceAddress()+SXPortEnum.REGISTER.getKey());
        return sxRegister;
    }
}
